<?php

namespace app\index\controller;


use think\Db;
use think\Request;
use think\View;
use app\index\model\Article as mArticle;

class Article extends Base
{
    public function _initialize()
    {
        parent::_initialize();

        //获取文章的推荐标签
        Base::recommend('article');
    }

    /*列表页*/
    public function index(Request $request)
    {

        //每页显示多少条
        $limit = $this->systemConfig['other_setting']['article_page'];
        //当前是第几页
        $page = 1;

        //初始子栏目ID
        $first_column['id'] = 0;

//        halt($request->param());

        /*是否是默认列表查询*/
        if (!$request->has('column_id')){
            //没有子栏目查询，查找訪栏目下是否有子栏目，有就默认返回第一个子元素的列表
            $sub_column = [];

            foreach ($this->columnData as $k => $v) {
                if ($request->has('cid') && ($v['id'] == $request->param('cid'))) {
                    $sub_column = $v['children'];
                }
                if (!$request->has('cid') && ($v['name_en'] == 'ARTICLE')) {
                    $sub_column = $v['children'];
                }
            }
            //重置数组内部指针，确保指向第一个元素
            reset($sub_column);
            $first_column = current($sub_column);
        }

        $map['column_id'] = $request->isGet() && $request->has('column_id') ? $request->param('column_id') : $first_column['id'];


        //是否是分页跳转  每页显示多少条
        $limit = $request->isGet() && $request->has('limit') ? $request->param('limit') : $limit;
        //是否有参数  当前是第几页
        $page = $request->isGet() && $request->has('page') ? $request->param('page') : $page;


        $data = Db::name('Article')->where($map)->order('id', 'desc')->paginate($limit, FALSE, [
            'page' => $page,
            'query' => [$map],
        ])->toArray();
        $data['limit'] = $limit;
//        halt($data);
        $this->assign(['data' => $data]);

            return view();
    }

    /*详情页*/
    public function detail(Request $request)
    {
        if ($request->isGet() && $request->has('id')) {
            //有人访问时，点击数自增1
            Db::name('article')->where('id', $request->param('id'))->setInc('hits');


            //是否是分页跳转  每页显示多少条
            $limit = $request->isGet() && $request->has('limit') ? $request->param('limit') : 1;
            //是否有参数  当前是第几页
            $page = $request->isGet() && $request->has('page') ? $request->param('page') : 1;


            //获取当前ID文章内容
            $data['detail'] = mArticle::read($request->param('id'),$page,$limit);

            //文章内容留言分页数据调用
            $message = $data['detail']['messages'];
            unset($data['detail']['messages']);
//            halt($message);
            $this->assign('data', $message);

            //获取上下篇
            self::get_pre_next($data['detail']['column_id'], $data['detail']['id'], 'article');

//            halt($data);
            return $this->fetch('', $data);
        } else {
            return $this->error('请求参数错误', '/article.html');
        }

    }


}
